/**
 * 主应用逻辑
 * 整合所有功能模块，实现完整的客户详情查询流程
 */

// 应用主类
class WeWorkApp {
    constructor() {
        this.isInitialized = false;
        this.currentCustomerId = null;
        this.currentCustomerData = null;
        
        // DOM元素引用
        this.elements = {};
        
        // 状态管理
        this.state = {
            loading: false,
            error: null,
            customerData: null
        };
        
        // 绑定方法上下文
        this.handleSearch = this.handleSearch.bind(this);
        this.handleRetry = this.handleRetry.bind(this);
        this.handleRefresh = this.handleRefresh.bind(this);
        
        window.AppUtils.log('WeWork应用初始化');
    }
    
    /**
     * 初始化应用
     */
    async init() {
        try {
            window.AppUtils.log('开始初始化应用');
            
            // 1. 初始化DOM元素引用
            this.initDOMElements();
            
            // 2. 绑定事件监听器
            this.bindEventListeners();
            
            // 3. 显示加载状态
            this.showLoading('正在初始化企业微信环境...');
            
            // 4. 初始化企业微信JSSDK
            const initSuccess = await window.WeChatUtils.autoInit();
            
            if (!initSuccess && !window.AppConfig.development.enableMockData) {
                throw new Error('企业微信环境初始化失败');
            }
            
            // 5. 获取客户ID
            await this.loadCustomerId();
            
            // 6. 如果有客户ID，自动加载客户详情
            if (this.currentCustomerId) {
                await this.loadCustomerDetail(this.currentCustomerId);
            } else {
                this.showEmptyState('请输入客户ID进行查询');
            }
            
            this.isInitialized = true;
            window.AppUtils.log('应用初始化完成');
            
        } catch (error) {
            window.AppUtils.error('应用初始化失败:', error);
            this.showError('应用初始化失败: ' + error.message);
        }
    }
    
    /**
     * 初始化DOM元素引用
     */
    initDOMElements() {
        this.elements = {
            // 加载状态
            loadingContainer: document.getElementById('loading-container'),
            loadingText: document.getElementById('loading-text'),
            
            // 主内容
            mainContent: document.getElementById('main-content'),
            
            // 搜索区域
            searchInput: document.getElementById('search-input'),
            searchButton: document.getElementById('search-button'),
            refreshButton: document.getElementById('refresh-button'),
            
            // 客户详情
            customerDetail: document.getElementById('customer-detail'),
            customerAvatar: document.getElementById('customer-avatar'),
            customerName: document.getElementById('customer-name'),
            customerType: document.getElementById('customer-type'),
            customerGender: document.getElementById('customer-gender'),
            customerCorp: document.getElementById('customer-corp'),
            customerPosition: document.getElementById('customer-position'),
            followUsersContainer: document.getElementById('follow-users'),
            
            // 空状态
            emptyState: document.getElementById('empty-state'),
            emptyMessage: document.getElementById('empty-message'),
            
            // 错误状态
            errorState: document.getElementById('error-state'),
            errorMessage: document.getElementById('error-message'),
            retryButton: document.getElementById('retry-button')
        };
        
        // 检查必要元素是否存在
        const requiredElements = ['loadingContainer', 'mainContent', 'searchInput', 'searchButton'];
        for (const elementKey of requiredElements) {
            if (!this.elements[elementKey]) {
                throw new Error(`必要的DOM元素未找到: ${elementKey}`);
            }
        }
        
        window.AppUtils.log('DOM元素初始化完成');
    }
    
    /**
     * 绑定事件监听器
     */
    bindEventListeners() {
        // 搜索按钮点击
        if (this.elements.searchButton) {
            this.elements.searchButton.addEventListener('click', this.handleSearch);
        }
        
        // 搜索输入框回车
        if (this.elements.searchInput) {
            this.elements.searchInput.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') {
                    this.handleSearch();
                }
            });
            
            // 输入框变化时清除错误状态
            this.elements.searchInput.addEventListener('input', () => {
                this.clearError();
            });
        }
        
        // 刷新按钮点击
        if (this.elements.refreshButton) {
            this.elements.refreshButton.addEventListener('click', this.handleRefresh);
        }
        
        // 重试按钮点击
        if (this.elements.retryButton) {
            this.elements.retryButton.addEventListener('click', this.handleRetry);
        }
        
        // 企业微信事件监听
        window.WeChatWork.on('ready', () => {
            window.AppUtils.log('企业微信JSSDK就绪');
        });
        
        window.WeChatWork.on('error', (error) => {
            window.AppUtils.error('企业微信JSSDK错误:', error);
        });
        
        window.AppUtils.log('事件监听器绑定完成');
    }
    
    /**
     * 加载客户ID
     */
    async loadCustomerId() {
        try {
            this.currentCustomerId = await window.WeChatUtils.getCustomerId();
            
            if (this.currentCustomerId && this.elements.searchInput) {
                this.elements.searchInput.value = this.currentCustomerId;
            }
            
            window.AppUtils.log('客户ID加载完成:', this.currentCustomerId);
        } catch (error) {
            window.AppUtils.warn('无法自动获取客户ID:', error.message);
            // 不抛出错误，允许用户手动输入
        }
    }
    
    /**
     * 加载客户详情
     * @param {string} externalUserId - 外部用户ID
     */
    async loadCustomerDetail(externalUserId) {
        if (!externalUserId || !externalUserId.trim()) {
            this.showEmptyState('请输入有效的客户ID');
            return;
        }
        
        try {
            this.showLoading('正在加载客户详情...');
            
            window.AppUtils.log('开始加载客户详情:', externalUserId);
            
            // 调用API获取客户详情
            const response = await window.API.getCustomerDetail(externalUserId.trim());
            
            if (response.data && response.data.data) {
                this.currentCustomerData = response.data.data;
                this.displayCustomerDetail(this.currentCustomerData);
                window.AppUtils.log('客户详情加载成功:', this.currentCustomerData);
            } else {
                throw new Error('客户详情数据格式错误');
            }
            
        } catch (error) {
            window.AppUtils.error('加载客户详情失败:', error);
            this.showError('加载客户详情失败: ' + error.message);
        }
    }
    
    /**
     * 显示客户详情
     * @param {Object} customerData - 客户数据
     */
    displayCustomerDetail(customerData) {
        try {
            // 隐藏其他状态
            this.hideAllStates();
            
            // 显示客户详情容器
            if (this.elements.customerDetail) {
                this.elements.customerDetail.style.display = 'block';
            }
            
            // 填充基本信息
            this.fillBasicInfo(customerData);
            
            // 填充跟进用户信息
            this.fillFollowUsers(customerData.followUsers || []);
            
            // 显示主内容
            if (this.elements.mainContent) {
                this.elements.mainContent.style.display = 'block';
            }
            
            window.AppUtils.log('客户详情显示完成');
            
        } catch (error) {
            window.AppUtils.error('显示客户详情失败:', error);
            this.showError('显示客户详情失败: ' + error.message);
        }
    }
    
    /**
     * 填充基本信息
     * @param {Object} customerData - 客户数据
     */
    fillBasicInfo(customerData) {
        // 头像
        if (this.elements.customerAvatar) {
            this.elements.customerAvatar.src = customerData.avatar || window.AppConfig.ui.defaultAvatar;
            this.elements.customerAvatar.alt = customerData.name || '客户头像';
        }
        
        // 姓名
        if (this.elements.customerName) {
            this.elements.customerName.textContent = customerData.name || '未知';
        }
        
        // 类型
        if (this.elements.customerType) {
            const typeText = this.getCustomerTypeText(customerData.type);
            this.elements.customerType.textContent = typeText;
        }
        
        // 性别
        if (this.elements.customerGender) {
            const genderText = this.getGenderText(customerData.gender);
            this.elements.customerGender.textContent = genderText;
        }
        
        // 公司
        if (this.elements.customerCorp) {
            const corpName = customerData.corpName || 
                           customerData.externalProfile?.externalCorpName || 
                           '未知公司';
            this.elements.customerCorp.textContent = corpName;
        }
        
        // 职位
        if (this.elements.customerPosition) {
            this.elements.customerPosition.textContent = customerData.position || '未知职位';
        }
    }
    
    /**
     * 填充跟进用户信息
     * @param {Array} followUsers - 跟进用户列表
     */
    fillFollowUsers(followUsers) {
        if (!this.elements.followUsersContainer) {
            return;
        }
        
        // 清空现有内容
        this.elements.followUsersContainer.innerHTML = '';
        
        if (!followUsers || followUsers.length === 0) {
            this.elements.followUsersContainer.innerHTML = '<p class="no-follow-users">暂无跟进用户信息</p>';
            return;
        }
        
        // 创建跟进用户列表
        followUsers.forEach((followUser, index) => {
            const followUserElement = this.createFollowUserElement(followUser, index);
            this.elements.followUsersContainer.appendChild(followUserElement);
        });
    }
    
    /**
     * 创建跟进用户元素
     * @param {Object} followUser - 跟进用户数据
     * @param {number} index - 索引
     * @returns {HTMLElement} 跟进用户元素
     */
    createFollowUserElement(followUser, index) {
        const div = document.createElement('div');
        div.className = 'follow-user-item';
        
        const createTime = followUser.createTime ? 
            window.AppUtils.formatDate(new Date(followUser.createTime)) : 
            '未知时间';
        
        const tags = followUser.tags || [];
        const tagsHtml = tags.map(tag => 
            `<span class="tag" title="${tag.groupName || ''}">${tag.tagName || ''}</span>`
        ).join('');
        
        const addWayText = this.getAddWayText(followUser.addWay?.addWay);
        
        div.innerHTML = `
            <div class="follow-user-header">
                <h4>跟进用户 ${index + 1}</h4>
                <span class="follow-time">${createTime}</span>
            </div>
            <div class="follow-user-content">
                <div class="follow-user-info">
                    <p><strong>用户ID:</strong> ${followUser.userId || '未知'}</p>
                    <p><strong>备注:</strong> ${followUser.remark || '无'}</p>
                    <p><strong>描述:</strong> ${followUser.description || '无'}</p>
                    <p><strong>添加方式:</strong> ${addWayText}</p>
                    ${followUser.remarkCorpName ? `<p><strong>备注公司:</strong> ${followUser.remarkCorpName}</p>` : ''}
                    ${followUser.remarkMobiles && followUser.remarkMobiles.length > 0 ? 
                        `<p><strong>备注手机:</strong> ${followUser.remarkMobiles.join(', ')}</p>` : ''}
                </div>
                ${tags.length > 0 ? `<div class="follow-user-tags">
                    <strong>标签:</strong>
                    <div class="tags-container">${tagsHtml}</div>
                </div>` : ''}
            </div>
        `;
        
        return div;
    }
    
    /**
     * 获取客户类型文本
     * @param {number} type - 类型代码
     * @returns {string} 类型文本
     */
    getCustomerTypeText(type) {
        const typeMap = {
            1: '微信用户',
            2: '企业微信用户'
        };
        return typeMap[type] || '未知类型';
    }
    
    /**
     * 获取性别文本
     * @param {number} gender - 性别代码
     * @returns {string} 性别文本
     */
    getGenderText(gender) {
        const genderMap = {
            0: '未知',
            1: '男',
            2: '女'
        };
        return genderMap[gender] || '未知';
    }
    
    /**
     * 获取添加方式文本
     * @param {number} addWay - 添加方式代码
     * @returns {string} 添加方式文本
     */
    getAddWayText(addWay) {
        const addWayMap = {
            0: '未知来源',
            1: '扫描二维码',
            2: '搜索手机号',
            3: '名片分享',
            4: '群聊',
            5: '手机通讯录',
            6: '微信联系人',
            7: '来自微信的咨询',
            8: '微信群',
            9: '邮件',
            201: '内部成员共享',
            202: '管理员/负责人分配'
        };
        return addWayMap[addWay] || '其他方式';
    }
    
    /**
     * 显示加载状态
     * @param {string} message - 加载消息
     */
    showLoading(message = '加载中...') {
        this.hideAllStates();
        
        if (this.elements.loadingContainer) {
            this.elements.loadingContainer.style.display = 'flex';
        }
        
        if (this.elements.loadingText) {
            this.elements.loadingText.textContent = message;
        }
        
        this.state.loading = true;
        this.state.error = null;
    }
    
    /**
     * 显示空状态
     * @param {string} message - 空状态消息
     */
    showEmptyState(message = '暂无数据') {
        this.hideAllStates();
        
        if (this.elements.emptyState) {
            this.elements.emptyState.style.display = 'block';
        }
        
        if (this.elements.emptyMessage) {
            this.elements.emptyMessage.textContent = message;
        }
        
        if (this.elements.mainContent) {
            this.elements.mainContent.style.display = 'block';
        }
        
        this.state.loading = false;
        this.state.error = null;
    }
    
    /**
     * 显示错误状态
     * @param {string} message - 错误消息
     */
    showError(message = '发生错误') {
        this.hideAllStates();
        
        if (this.elements.errorState) {
            this.elements.errorState.style.display = 'block';
        }
        
        if (this.elements.errorMessage) {
            this.elements.errorMessage.textContent = message;
        }
        
        if (this.elements.mainContent) {
            this.elements.mainContent.style.display = 'block';
        }
        
        this.state.loading = false;
        this.state.error = message;
        
        // 显示错误提示
        window.AppUtils.showMessage(message, 'error');
    }
    
    /**
     * 清除错误状态
     */
    clearError() {
        if (this.elements.errorState) {
            this.elements.errorState.style.display = 'none';
        }
        
        this.state.error = null;
    }
    
    /**
     * 隐藏所有状态
     */
    hideAllStates() {
        const stateElements = [
            'loadingContainer',
            'customerDetail',
            'emptyState',
            'errorState'
        ];
        
        stateElements.forEach(elementKey => {
            if (this.elements[elementKey]) {
                this.elements[elementKey].style.display = 'none';
            }
        });
        
        this.state.loading = false;
    }
    
    /**
     * 处理搜索
     */
    async handleSearch() {
        const searchValue = this.elements.searchInput?.value?.trim();
        
        if (!searchValue) {
            window.AppUtils.showMessage('请输入客户ID', 'warning');
            return;
        }
        
        this.currentCustomerId = searchValue;
        await this.loadCustomerDetail(searchValue);
    }
    
    /**
     * 处理刷新
     */
    async handleRefresh() {
        if (this.currentCustomerId) {
            await this.loadCustomerDetail(this.currentCustomerId);
        } else {
            await this.loadCustomerId();
            if (this.currentCustomerId) {
                await this.loadCustomerDetail(this.currentCustomerId);
            }
        }
    }
    
    /**
     * 处理重试
     */
    async handleRetry() {
        if (this.currentCustomerId) {
            await this.loadCustomerDetail(this.currentCustomerId);
        } else {
            await this.init();
        }
    }
    
    /**
     * 获取当前状态
     * @returns {Object} 当前状态
     */
    getState() {
        return { ...this.state };
    }
    
    /**
     * 获取当前客户数据
     * @returns {Object} 当前客户数据
     */
    getCurrentCustomerData() {
        return this.currentCustomerData;
    }
}

// 应用实例
let app = null;

// DOM加载完成后初始化应用
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initApp);
} else {
    initApp();
}

/**
 * 初始化应用
 */
async function initApp() {
    try {
        window.AppUtils.log('开始初始化WeWork应用');
        
        // 创建应用实例
        app = new WeWorkApp();
        
        // 将应用实例暴露到全局（用于调试）
        if (window.AppConfig.development.enableDebugLog) {
            window.WeWorkApp = app;
        }
        
        // 初始化应用
        await app.init();
        
        window.AppUtils.log('WeWork应用初始化完成');
        
    } catch (error) {
        window.AppUtils.error('应用初始化失败:', error);
        
        // 显示初始化失败的错误页面
        document.body.innerHTML = `
            <div class="init-error">
                <div class="error-content">
                    <h2>应用初始化失败</h2>
                    <p class="error-message">${error.message}</p>
                    <button onclick="location.reload()" class="retry-button">重新加载</button>
                </div>
            </div>
            <style>
                .init-error {
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    min-height: 100vh;
                    padding: 20px;
                    background-color: #f5f5f5;
                }
                .error-content {
                    text-align: center;
                    background: white;
                    padding: 40px;
                    border-radius: 8px;
                    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
                    max-width: 400px;
                }
                .error-content h2 {
                    color: #f5222d;
                    margin-bottom: 16px;
                }
                .error-message {
                    color: #666;
                    margin-bottom: 24px;
                    line-height: 1.5;
                }
                .retry-button {
                    background-color: #1890ff;
                    color: white;
                    border: none;
                    padding: 12px 24px;
                    border-radius: 6px;
                    cursor: pointer;
                    font-size: 14px;
                }
                .retry-button:hover {
                    background-color: #40a9ff;
                }
            </style>
        `;
    }
}

// 全局错误处理
window.addEventListener('error', (event) => {
    window.AppUtils.error('全局错误:', event.error);
});

window.addEventListener('unhandledrejection', (event) => {
    window.AppUtils.error('未处理的Promise拒绝:', event.reason);
});

// 调试信息
if (window.AppConfig.development.enableDebugLog) {
    window.AppUtils.log('主应用脚本已加载');
}